package sparesarray;

/*
* 稀疏数组实现
* */


import java.io.*;

public class SpareArray {
    public static void main(String[] args) throws IOException {
        // 创建一个二维数组表示棋盘
        int[][] chessArray = new int[11][11];

        // 赋值,0表示没有棋子,1表示黑子,2表示白字
        chessArray[1][2] = 1;
        chessArray[2][3] = 2;

        // 遍历打印
        int sum = 0;
        for (int i = 0; i < chessArray.length; i++) {
            for (int j = 0; j < chessArray[i].length; j++) {
                if(chessArray[i][j] != 0){
                    sum++;
                }
                System.out.printf("%d\t",chessArray[i][j]);
            }
            System.out.println();
        }

        System.out.println("数组中有效元素个数为"+sum);

        // 创建稀疏数组 行为sum+1 列为三
        int[][] spareArray = new int[sum+1][3];
        spareArray[0][0] = 11;
        spareArray[0][1] = 11;
        spareArray[0][2] = sum;

        int count = 0;
        for (int i = 0; i <11 ; i++) {
            for (int j = 0; j <11; j++) {
                if(chessArray[i][j] != 0){
                    count++;
                    spareArray[count][0] = i;
                    spareArray[count][1] = j;
                    spareArray[count][2] =chessArray[i][j];
                }
            }
        }

        // 遍历稀疏数组
        for(int [] data:spareArray){
            for (int i = 0; i < 3; i++) {
                System.out.printf("%d\t",data[i]);
            }
            System.out.println();
        }

        // 将稀疏数组存到文件中
        FileOutputStream fos = new FileOutputStream("a.txt");

        for (int i = 0; i <spareArray.length ; i++) {
            for (int j = 0; j <3 ; j++) {
                fos.write(spareArray[i][j]);
            }
        }
        fos.close();



        // 恢复二维数组
        FileReader fr = new FileReader("a.txt");
        int read1 = fr.read();
        int read2 = fr.read();
        int read3 = fr.read();

        //int[][] newArr = new int[spareArray[0][0]][spareArray[0][1]];
        int[][] newArr = new int[read1][read2];

/*        for (int i = 1; i < spareArray.length; i++) {
            newArr[spareArray[i][0]][spareArray[i][1]] = spareArray[i][2];
        } */
        for (int i = 0; i < read3; i++) {
            read1 = fr.read();
            read2 = fr.read();
            int read4 = fr.read();
            newArr[read1][read2] = read4;
        }
        fr.close();

        // 遍历二维数组
        for (int i = 0; i < spareArray[0][0]; i++) {
            for (int j = 0; j < spareArray[0][1]; j++) {
                System.out.printf("%d\t",newArr[i][j]);
            }
            System.out.println();
        }
    }
}
